package com.hongxun.design.fragments;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;

import com.hongxun.design.activitys.HomePageActivity;
import com.hongxun.design.adapters.EncyclopediasAdapter;
import com.hongxun.design.bean.CategoryItemBean;
import com.hongxun.design.bean.EncyclopediaBean;
import com.hongxun.design.constant.Constant;
import com.hongxun.design.listeners.MClickListener;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.ui.ui_listview.refreshlist.SwipeRefreshListView;
import com.hongxun.design.utils.DensityUtil;
import com.hongxun.design.utils.FragmentUtil;
import com.hongxun.design.utils.InputUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 百科界面*
 */
public class EncyclopediasFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {
    SwipeRefreshListView encycopedias_list;
    LinearLayout titles;
    String FileTag = "EncyclopediasFragment";
    private Handler categoryHandler;
    private Handler encyclopediaListHandler;
    List<CategoryItemBean> data;
    List<EncyclopediaBean> currData = new ArrayList<>();
    List<List<EncyclopediaBean>> allData = new ArrayList<>();
    EncyclopediasAdapter mAdapter;
    int currPosition = 0;
    String currId = "";
    String currName = "";
    int startNum = 0;
    int addNum =  MyApp.addNum;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View newsLayout = inflater.inflate(R.layout.fragment_encyclopediaslayout, container,
                false);
        findView(newsLayout);

        return newsLayout;
    }

    @Override
    void findView(View v) {
        super.findView(v);
        if (encycopedias_list == null)
            encycopedias_list = (SwipeRefreshListView) v.findViewById(R.id.encycopedias_list);
        encycopedias_list.setOnRefreshListener(this);
        titles = (LinearLayout) v.findViewById(R.id.encycopedias_titles);

        initialization();
    }


    @Override
    void initialization() {
        super.initialization();
        //获取缓存
        data = MyApp.File.LoadFileData_Category(FileTag + "title");
        addCategoryHandler();//标题数据操作handler
        addEncyclopediaListHandler();//列表数据操作handler
        if (data.size() > 0) {
            categoryHandler.sendEmptyMessage(1);
        }
        getTitle();
    }

    /**
     * *******************************网络请求******************************************************
     */


    /**
     * 获取标题*
     */
    private void getTitle() {
        MyApp.HTTP.getCategory(categoryHandler, HttpStringUtil.SUCCESSED);
    }

    /**
     * 获取列表*
     */
    private void getListById(String id) {
        currId = id;
        currName = ((HomePageActivity) getActivity()).headPanel.getSearchWords();
        MyApp.HTTP.getEncyclopediaList(encyclopediaListHandler, HttpStringUtil.SUCCESSED, currName, id, startNum, startNum + addNum);
    }

    /**
     * *******************************handler操作接收******************************************************
     */

    private void addCategoryHandler() {
        categoryHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        String s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            if (data == null) {
                                data = FastJsonUtil.JsonToGetCategory((String) msg.obj);
                            } else {
                                data.clear();
                                data.addAll(FastJsonUtil.JsonToGetCategory((String) msg.obj));
                            }
                            if (data != null) {
                                MyApp.File.SaveFileData(FileTag + "title", "{\"category\":" + JSON.toJSONString(data) + "}");
                                categoryHandler.sendEmptyMessage(1);
                            }

                        } else {
                            ToastShow.showShort(getActivity(), s);
                        }
                        break;
                    case 1:
                        addTitles();
                       if (textviews.size()>0)textviews.get(0).callOnClick();
                        break;
                    case HttpStringUtil.ERROR:

                        break;
                }
            }
        };
    }


    private void addEncyclopediaListHandler() {
        encyclopediaListHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        String s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            currData.clear();
                            currData.addAll(FastJsonUtil.JsonToGetEncyclopediaList((String) msg.obj));
                            allData.get(currPosition).clear();
                            allData.get(currPosition).addAll(currData);
                            MyApp.File.SaveFileData(FileTag + currId, "{\"encyclopediaList\":" + JSON.toJSONString(currData) + "}");
                            startNum += addNum;
                            encyclopediaListHandler.sendEmptyMessage(1);
                        } else {
                            ToastShow.showShort(getActivity(), s);
                        }
                        break;
                    case 1:
                        if (mAdapter == null) {
                            mAdapter = new EncyclopediasAdapter(getActivity(), currData);
                            encycopedias_list.setAdapter(mAdapter);
                            encycopedias_list.setFragment(baseFragment);
                            encycopedias_list.setCanScroll(true);
                            encycopedias_list.setDivider(1);
                        } else {
                            encycopedias_list.update();
                            encycopedias_list.setRefreshing(false);
                            encycopedias_list.removeFooterView();
                        }
                        break;
                    case HttpStringUtil.ADDMROE:
                        currData.addAll(FastJsonUtil.JsonToGetEncyclopediaList((String) msg.obj));
                        startNum += addNum;
                        encyclopediaListHandler.sendEmptyMessage(1);
                        break;
                    case HttpStringUtil.ERROR:
                        encycopedias_list.setRefreshing(false);
                        break;
                }
            }
        };

    }
    /**
     * *******************************操作方法******************************************************
     */
    /**
     * 动态加载标题*
     */


    private synchronized void addTitles() {
        titles.removeAllViews();
        textviews.clear();
        if (data!=null&&data.size() > 0) {
            int i = 0;
            for (CategoryItemBean b : data) {
                allData.add(new ArrayList<EncyclopediaBean>());
                addView(i, b);
                i++;
            }

        }
    }

    List<TextView> textviews = new ArrayList<>();

    private void addView(int i, CategoryItemBean b) {
        RelativeLayout layout = new RelativeLayout(getActivity());
        TextView view = new TextView(getActivity());
        view.setText("  " + b.getName() + "  ");
        view.setTextSize(16);
        view.setTextColor(getResources().getColor(R.color.title));
        view.setGravity(Gravity.CENTER);
        view.setSingleLine();
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, DensityUtil.dip2px(getActivity(), 36));
        layoutParams.setMargins(10, 0,10, 0);//4个参数按顺序分别是左上右下
        // RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, DensityUtil.dip2px(getActivity(), 36));
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        layout.addView(view, layoutParams);
        textviews.add(view);
        view.setOnClickListener(new MClickListener(i, b) {
            @Override
            public void onClick(View view, int position, Object msg) {
                InputUtil.closeInput(getActivity());
                if (textviews.size() > 0) {
                    for (TextView textView : textviews) {
                        textView.setTextColor(getResources().getColor(R.color.gray));
                        textView.setBackground(null);
                    }
                }
                view.setBackgroundResource(R.drawable.circular6_blue_line3);
                ((TextView) view).setTextColor(getResources().getColor(R.color.caikan_bule));
                CategoryItemBean bean = (CategoryItemBean) msg;
                currPosition = position;
                currId = bean.getCategory_id();
                if (allData.get(position).size() > 0) {
                    currData.clear();
                    currData.addAll(allData.get(position));
                    encyclopediaListHandler.sendEmptyMessage(1);
                } else {
                    startNum = 0;
                    currData.clear();
                    if (mAdapter!=null){
                        encyclopediaListHandler.sendEmptyMessage(1);
                    }

                    currData.addAll(MyApp.File.LoadFileData_EncyclopediaBean(FileTag + bean.getCategory_id()));
                    MyLog.L(MString.SUCCESSED + " currData=" + JSON.toJSONString(currData));
                    if (currData.size() > 0) {
                        encyclopediaListHandler.sendEmptyMessage(1);
                    }
                    getListById(bean.getCategory_id());
                }
            }
        });
        final float scale = getActivity().getResources().getDisplayMetrics().density;
        int left = (int) (15 * scale + 0.5f);
        titles.setPadding(left, 0, left, 0);
        titles.addView(layout, RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

    }

    /**
     * listview刷新函数*
     */
    @Override
    public void onRefresh() {
        startNum = 0;
        currData.clear();
        if (mAdapter!=null){
            encyclopediaListHandler.sendEmptyMessage(1);
        }
        currData.addAll(MyApp.File.LoadFileData_EncyclopediaBean(FileTag + currId));
        getListById(currId);
    }


    @Override
    public void Refresh() {
        super.Refresh();
        if (data==null||data.size()==0){
            getTitle();
        }
    }

    @Override
    public void addMore() {
        super.addMore();
        MyApp.HTTP.getEncyclopediaList(encyclopediaListHandler, HttpStringUtil.ADDMROE, currName, currId, startNum, startNum + addNum);

    }

    @Override
    public void onResume() {
        super.onResume();
        FragmentUtil.currFragTag = Constant.FRAGMENT_FLAG_ENCYCLOPEDIAS;
        baseFragment = this;
    }


}
